package service

import (
	"context"

	alertv1 "github.com/devops-smartbot/devops-smartbot/proto/gen/go/alert/v1"
	"github.com/devops-smartbot/devops-smartbot/services/alert-service/internal/model"
	"github.com/devops-smartbot/devops-smartbot/services/alert-service/internal/repository"
)

// Service exposes alert business operations.
//go:generate mockgen -destination=../mocks/service.go -package=mocks . Service
type Service interface {
	ListAlerts(ctx context.Context, req *alertv1.ListAlertsRequest) ([]model.Alert, int64, error)
	GetAlert(ctx context.Context, id string) (*model.Alert, error)
}

// alertService implements Service using a repository.
type alertService struct {
	repo repository.Repository
}

// NewAlertService creates a new service instance.
func NewAlertService(repo repository.Repository) Service {
	return &alertService{repo: repo}
}

func (s *alertService) ListAlerts(ctx context.Context, req *alertv1.ListAlertsRequest) ([]model.Alert, int64, error) {
	pagination := req.GetPagination()
	page := pagination.GetPage()
	if page <= 0 {
		page = 1
	}
	pageSize := pagination.GetPageSize()
	if pageSize <= 0 {
		pageSize = 20
	}

	filter := repository.Filter{
		Severity: req.GetSeverity(),
		Status:   req.GetStatus(),
		Limit:    int64(pageSize),
		Offset:   int64((page - 1) * pageSize),
	}

	return s.repo.ListAlerts(ctx, filter)
}

func (s *alertService) GetAlert(ctx context.Context, id string) (*model.Alert, error) {
	return s.repo.GetAlert(ctx, id)
}

var _ Service = (*alertService)(nil)
